package com.cjl.android.handlerthread;

import com.cjl.android.handler.Looper;

public class HandlerThread extends Thread{

    private Looper mLooper;

    public HandlerThread(String name) {
        super(name);
    }

    @Override
    public void run() {
        Looper.prepare();
        synchronized (this){
            mLooper = Looper.myLooper();
            notifyAll();
        }
        onLooperPrepared();
        Looper.loop();
    }

    protected void onLooperPrepared() {

    }

    public Looper getLooper(){
        if (!isAlive()){
            return null;
        }
        synchronized (this){
            //线程启动后,若mLooper null,一直等待直到创建成功
            while (isAlive() && mLooper == null){
                try {
                    wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
        return mLooper;
    }

}
